package cn.wolfcode.wolf2world.service.impl;

import cn.wolfcode.wolf2world.domain.StrategyComment;
import cn.wolfcode.wolf2world.query.StrategyCommentQueryObject;
import cn.wolfcode.wolf2world.repository.StrategyCommentRepository;
import cn.wolfcode.wolf2world.service.StrategyCommentService;
import cn.wolfcode.wolf2world.utils.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author 杨兴健
 * @Date 2020-08-16 21:27
 */
@Service
public class StrategyCommentServiceImpl implements StrategyCommentService {
    @Autowired
    private StrategyCommentRepository strategyCommentRepository;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void insert(StrategyComment strategyComment) {
        strategyComment.setId(null);
        strategyCommentRepository.insert(strategyComment);
    }

    @Override
    public void update(StrategyComment strategyComment) {
        strategyCommentRepository.save(strategyComment);
    }

    @Override
    public void delete(String id) {
        strategyCommentRepository.deleteById(id);
    }

    @Override
    public StrategyComment get(String id) {
        return strategyCommentRepository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyComment> list() {
        return strategyCommentRepository.findAll();
    }

    /**
    * 攻略评论高级查询
    * @param qo 查询条件
    * @return
    */
    @Override
    public Page<StrategyComment> query(StrategyCommentQueryObject qo) {

        Query query = new Query();
        if (qo.getStrategyId() != null) {
            query.addCriteria(Criteria.where("strategyId").is(qo.getStrategyId()));
        }
        return DBHelper.getPage(mongoTemplate,query,qo,StrategyComment.class, Sort.Direction.ASC,"createTime");
    }

    /**
     * 新增或编辑攻略评论
     * @param strategyComment
     */
    @Override
    public void saveOrUpdate(StrategyComment strategyComment) {
        if (StringUtils.hasLength(strategyComment.getId())) {
            //编辑
            this.update(strategyComment);
        }else {
            //新增
            this.insert(strategyComment);
        }
    }
}
